﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ET;
using Marx.Utils;

namespace Marx
{
    public class ConfigLoader : Singleton<ConfigLoader>
    {
        public class ConfigContentItem
        {
            public string FileName;
            public string ClsName;
            public bool IsArray;
        }

        private string templateRootPath_;
        private string templateDetailFile_;
        private List<ConfigContentItem> configContents_ = new List<ConfigContentItem>();
        private Dictionary<string, ConfigContentItem> configDict_ = new Dictionary<string, ConfigContentItem>();

        public void Initialize(string templatePath, string detailFile)
        {
            if(!templatePath.EndsWith("/"))
            {
                templateRootPath_ = templatePath + "/";
            }
            else
            {
                templateRootPath_ = templatePath;
            }
            templateDetailFile_ = detailFile;
        }

        public void LoadTemplateBegin()
        {
            var content = ResHelper.LoadText(templateDetailFile_);
            configContents_ = JsonHelper.FromJson<List<ConfigContentItem>>(content);

            foreach (var item in configContents_)
            {
                configDict_.Add(item.ClsName, item);
            }
        }

        internal void LoadHook(string templateTypeName, Action<string, bool, string> loader)
        {
            if(configDict_.TryGetValue(templateTypeName, out var item))
            {
                var content = ResHelper.LoadText(templateRootPath_ + item.FileName);
                loader.Invoke(content, item.IsArray, item.ClsName);
            }
            else
            {
                Log.Error("Template: [" + templateTypeName + "] was not found");
            }
        }

        public void LoadTemplateEnd()
        {
            ConfigDelayInit.InvokeDelayInitAction();
        }
    }
}
